import { parse } from 'querystring';
import cityData from './cityData';

const reg = /^((([Hh][Tt])|(Ff))[Tt][Pp][Ss]?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?$/;

export const isUrl = (path: string): boolean => reg.test(path);

//判断文件是否是图片
export const isAssetTypeAnImage = (ext: string) => {
	return /\.(png|PNG|jpe?g|JPE?G|gif|GIF|svg|SVG)(\?.*)?$/.test(ext);
}
//判断文件是word
export const isAssetTypeAnWord = (ext: string) => {
	return /\.(docx|doc|DOC|DOCX|xlsx|xls|XLSX|XLS)(\?.*)?$/.test(ext);
}
//判断文件是否多个
export const isNotOneFile = (ext: string) => {
	const flist = ext.split(',');
	if (flist.length > 1) {
		return true;
	}
	return false;
}

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

export function fixedZero(val: any) {
	return val * 1 < 10 ? `0${val}` : val;
}

export function formatDateIOS(val: any) {
	if (!val) return;
	const date = new Date(val);
	let y, m, day;
	y = date.getFullYear();
	m = fixedZero(date.getMonth() + 1);
	day = fixedZero(date.getDate());
	return y + '/' + m + '/' + day;
}
export function formatDateIOS2(val: any) {
	if (!val) return;
	const date = new Date(val);
	let y, m, day;
	y = date.getFullYear();
	m = fixedZero(date.getMonth() + 1);
	day = fixedZero(date.getDate());
	return y + '-' + m + '-' + day;
}
export function changeTimeFormat(time: any) {
	const date = new Date(time);
	const month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
	const currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
	const hh = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
	const mm = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
	const ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
	return date.getFullYear() + "-" + month + "-" + currentDate + " " + hh + ":" + mm + ":" + ss;
	//返回格式：yyyy-MM-dd hh:mm
}

// 获取上个月日期
export function getLastMonthDate() {
	const lastMonthDate = new Date(new Date().getTime() - 30 * 1000 * 60 * 60 * 24); //上月日期
	return formatDateIOS(lastMonthDate);
}

export function accSub(num1: number, num2: number) {
	let r1;
	let r2;
	try {
		r1 = num1.toString().split('.')[1].length;
	} catch (e) {
		r1 = 0;
	}
	try {
		r2 = num2.toString().split('.')[1].length;
	} catch (e) {
		r2 = 0;
	}
	const m = Math.pow(10, Math.max(r1, r2));
	const n = (r1 >= r2) ? r1 : r2;
	return (Math.round(num1 * m - num2 * m) / m).toFixed(n);
}


/**
	 * 小数相乘，解决丢失精度问题
	 * @param {Number} value1
	 * @param {Number} value2
	 */
export function accMul(value1: number = 0, value2: number = 0) {
	if (value1 == 0 || value2 == 0) {
		return 0;
	}
	let m = 0;
	const v1 = value1.toString();
	const v2 = value2.toString();
	m += v1.split(".")[1] ? v1.split(".")[1].length : 0;
	m += v2.split(".")[1] ? v2.split(".")[1].length : 0;
	const _v1 = Number(v1.replace(".", ""));
	const _v2 = Number(v2.replace(".", ""));
	return (_v1 * _v2) / Math.pow(10, m);
}


/**
	 * 除法，解决丢失精度问题
	 * @param {Number} value1 除数
	 * @param {*} value2 被除数
	*/
export function accDiv(value1: number = 0, value2: number = 0) {
	if (value1 == 0 || !value1) {
		return 0;
	}
	const v1 = value1.toString();
	const v2 = value2.toString();
	const m1 = v1.split(".")[1] ? v1.split(".")[1].length : 0;
	const m2 = v2.split(".")[1] ? v2.split(".")[1].length : 0;
	const _v1 = Number(v1.replace(".", ""));
	const _v2 = Number(v2.replace(".", ""));
	return accMul(_v1 / _v2, Math.pow(10, m2 - m1));
}

/**
 * 对数字进行三位分割
 * @param {*} value  需要进行分割的数字
 * @returns  返回分割后的数字串
 */

// 小数部分只显示两位小数，数字分割显示
export function NumFormat(value: string | number) {
	if (!value) return '0'
	let floatPart = '.00' // 预定义小数部分
	const value2Array = value.toString().split('.')
	// =2表示数据有小数位
	if (value2Array.length === 2) {
		floatPart = value2Array[1].toString() // 拿到小数部分
		const intPartFormat = value2Array[0].toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') // 将整数部分逢三一断
		if (floatPart.length === 1) {
			// 补0
			return intPartFormat + '.' + floatPart + '0'
		} else {
			return intPartFormat + '.' + floatPart
		}
	} else if (value2Array.length === 1) {
		return value2Array[0].toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
	} else {
		return '0'
	}
}

// 计算同比增长率
export function getRate(preNumber: number, newNUmber: number) {
	const decreaseValue = Number(accSub(Number(newNUmber) || 0, Number(preNumber) || 0));
	return accMul(Number(accDiv(decreaseValue, Number(preNumber) || 0).toFixed(2)), 100) + '% ';
}

export function getLetter(index: number) {
	const num = Number(index);
	const list = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
	return list[num];
}


// 获取当前月起止日期
export function getMonthStart() {
	const now = new Date(); // 当前日期
	const nowYear = now.getFullYear(); //当前年
	const nowMonth = now.getMonth(); //当前月 （值为0~11）注意此处范围
	const firstDay = new Date(nowYear, nowMonth, 1).getTime(); // 本月开始时间
	return firstDay
}

export function getMonthEnd() {
	const now = new Date(); // 当前日期
	const nowYear = now.getFullYear(); //当前年
	const nowMonth = now.getMonth(); //当前月 （值为0~11）注意此处范围
	const LastDay = new Date(nowYear, nowMonth + 1, 0).getTime(); // 本月结束时间
	return LastDay
}

export function getCity(key: any) {
	let city = cityData;
	if (key) {
		city = cityData.filter((item) => item.value == key)
	}
	return city
}

export function isIdCard(value: string) {
	const idCard = value;
	if (idCard.length == 15) {
		return _isValidityBrithBy15IdCard(idCard);
	} else if (idCard.length == 18) {
		const arrIdCard = idCard.split("");
		if (_isValidityBrithBy18IdCard(idCard) && _isTrueValidateCodeBy18IdCard(arrIdCard)) {
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function _isTrueValidateCodeBy18IdCard(arrIdCard: any[]) {
	let sum = 0;
	const Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1];
	const ValideCode = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2];
	if (arrIdCard[17].toLowerCase() == 'x') {
		arrIdCard[17] = 10;
	}
	for (let i = 0; i < 17; i++) {
		sum += Wi[i] * arrIdCard[i];
	}
	const valCodePosition = sum % 11;
	if (arrIdCard[17] == ValideCode[valCodePosition]) {
		return true;
	} else {
		return false;
	}
}

function _isValidityBrithBy18IdCard(idCard18: string) {
	const year = idCard18.substring(6, 10);
	const month = idCard18.substring(10, 12);
	const day = idCard18.substring(12, 14);
	const temp_date = new Date(Number(year), parseFloat(month) - 1, parseFloat(day));
	if (temp_date.getFullYear() != parseFloat(year) || temp_date.getMonth() != parseFloat(month) - 1 || temp_date.getDate() !=
		parseFloat(day)) {
		return false;
	} else {
		return true;
	}
}

function _isValidityBrithBy15IdCard(idCard15: string) {
	const year = idCard15.substring(6, 8);
	const month = idCard15.substring(8, 10);
	const day = idCard15.substring(10, 12);
	const temp_date = new Date(Number(year), parseFloat(month) - 1, parseFloat(day));

	if (temp_date.getYear() != parseFloat(year) || temp_date.getMonth() != parseFloat(month) - 1 || temp_date.getDate() !=
		parseFloat(day)) {
		return false;
	} else {
		return true;
	}
}

export function handleFileid(files: any[]) {
	let fid = '';
	files.forEach((img) => {
		if (img.fileId) {
			if (fid.length > 0) {
				fid = fid + ',' + img.fileId;
			} else {
				fid = img.fileId;
			}
		}
	});
	return fid;
};

export function handleFileUrl(ids: string, urls: string) {
	if (!ids || !urls) {
		console.log(111333);
		
		return []
	}
	const files: any[] = [];
	const fileIds = ids.split(',');
	console.log(fileIds);
	
	const fileUrls = urls.split(',');
	console.log(fileUrls,'fileUrls');
	
	fileIds.forEach(item => {
		if (item.length > 0) {
			for (let index = 0; index < fileUrls.length; index++) {
				const element = fileUrls[index];
				if (element.indexOf(item) > -1) {
					files.push({
						id: item,
						url: element,
						fileId: item,
						fileName: item,
						name: item,
						preview: element
					})
					fileUrls.splice(index, 1);
					break;
				}
			}
		}
	})
	return files;
};

/**
 * 删除URL中指定search参数,会将参数值一起删除
 * @param {string} url 地址字符串
 * @param {array} aParam 要删除的参数key数组，如['name','age']
 * @return {string} 返回新URL字符串
 */
export function ridUrlParam(url: string, params: any[]) {
	let replaceUrl = url;
	for (let index = 0; index < params.length; index++) {
		const item = params[index];
		const fromIndex = url.indexOf(item + "="); //必须加=号，避免参数值中包含item字符串
		if (fromIndex !== -1) {
			// 通过url特殊符号，计算出=号后面的的字符数，用于生成replace正则
			const startIndex = url.indexOf("=", fromIndex);
			const endIndex = url.indexOf("&", fromIndex);
			const hashIndex = url.indexOf("#", fromIndex);

			let regU: any;
			if (endIndex !== -1) {
				// 后面还有search参数的情况
				const num = endIndex - startIndex;
				regU = new RegExp(item + "=.{" + num + "}");
				replaceUrl = url.replace(regU, "");
			} else if (hashIndex !== -1) {
				// 有hash参数的情况
				const num1 = hashIndex - startIndex - 1;
				regU = new RegExp("&?" + item + "=.{" + num1 + "}");
				replaceUrl = url.replace(regU, "");
			} else {
				// search参数在最后或只有一个参数的情况
				regU = new RegExp("&?" + item + "=.+");
				replaceUrl = url.replace(regU, "");
			}
		}
	}
	const noSearchParam = url.indexOf("=");
	if (noSearchParam === -1) {
		replaceUrl = url.replace(/\?/, ""); // 如果已经没有参数，删除？号
	}
	return replaceUrl;
}
/**
 * 删除浏览器地址指定参数及值
 * @param {参数名，数组} paramNames 
 * @param {是否刷新} isRefresh 
 */
export function replaceHrefParam(paramNames: string, isRefresh: boolean) {
	const oUrl = window.location.href.toString();
	let nUrl;
	if (typeof paramNames == 'string') {
		nUrl = ridUrlParam(oUrl, [paramNames]);
	} else {
		nUrl = ridUrlParam(oUrl, paramNames);
	}
	const stateObject = {
		id: ""
	};
	const title = "";
	history.replaceState(stateObject, title, nUrl);
	if (isRefresh) {
		window.location.href = nUrl
	}
}
/**
 * 在浏览器地址添加指定键值对
 * @param {参数名} paramName 
 * @param {值} replaceWith 
 * @param {是否刷新} isRefresh 
 */
export function replaceParamVal(paramName: string, replaceWith: string, isRefresh: boolean) {
	const oUrl = window.location.href.toString();
	let nUrl;
	if (paramName && replaceWith) {
		if (oUrl.indexOf(paramName + "=" + replaceWith) > 1) {
			return;
		}
	}
	if (oUrl.indexOf(paramName) > 0) {
		const re = eval('/(' + paramName + '=)([^&]*)/gi');
		nUrl = oUrl.replace(re, paramName + '=' + replaceWith);
	} else {
		if (oUrl.indexOf("?") > 0) {
			nUrl = oUrl + "&" + paramName + "=" + replaceWith;
		} else {
			nUrl = oUrl + "?" + paramName + "=" + replaceWith;
		}
	}
	// this.location = nUrl;
	const stateObject = {
		id: ""
	};
	const title = "";
	history.replaceState(stateObject, title, nUrl);
	if (isRefresh) {
		window.location.href = nUrl
	}
}

export function getQueryVariable(variable: string) {
	const {
		href
	} = window.location;
	const query = href.split('?')[1];
	if (query) {
		const vars = query.split("&");
		for (let i = 0; i < vars.length; i++) {
			const pair = vars[i].split("=");
			if (pair[0] == variable) {
				return pair[1];
			}
		}
		return false;
	}
	return false;
}

//返回字符串中的链接地址及类型
export function filterByurls(urls: string) {
	if (typeof urls === 'string' && urls.length > 0) {
		const list = urls.split(',');
		const slist: any[] = [];
		list.forEach(value => {
			if (value.length > 0) {
				let type = '';
				let name = '';
				// //获取最后一个.的位置
				// var index = value.lastIndexOf(".");
				// //获取后缀
				// var ext = value.substr(index + 1);
				if (isAssetTypeAnImage(value)) {
					type = 'image';
				} else {
					type = 'file';
				}
				//获取地址最后一个“/”的下标
				const ts_indexof = value.lastIndexOf("/");
				//获取地址“/”之后的的内容
				const ts_indexText = value.substring(ts_indexof + 1);
				//获取地址“?”的下标
				const ts_beforeText = ts_indexText.indexOf("?");
				//获取 “/”到"?"之间的内容
				if (ts_beforeText < 0) {
					name = ts_indexText;
				} else {
					name = ts_indexText.substring(0, ts_beforeText);
				}

				slist.push({
					type: type,
					name: name,
					url: value
				});
			}
		})
		return slist;
	}
	return [];
}

// export function getCookie(name: string) {
//   const arr = document.cookie.split(";");
//   for (let i = 0; i < arr.length; i++) {
//     const arr2 = arr[i].split("=");
//     if (arr2[0] == name) {
//       return arr2[1];
//     }
//   }
//   return "";
// }

export function getCookie(key: string) {
	const _key = `${key}=`;
	const cookieStr = decodeURIComponent(document.cookie.replace(/;s*/ig, ';'));
	if (!cookieStr) {
		return '';
	}
	const arr = cookieStr.split(';');
	const curItem = arr.find(item => item.indexOf(_key) > -1);
	if (!curItem) {
		return '';
	}
	return curItem.trim().replace(_key, '');
}

export function setCookie(key: string, value: string, options: any) {
	const def = { path: '/', expires: 0 };
	const params = Object.assign({}, def, options);
	const d = new Date();
	if (!!params.expires) {
		d.setTime(d.getTime() + params.expires * 1000);
		params.expires = d.toUTCString();
	}

	const result = Object.keys(params).reduce((acc: string, akey) => {
		const curVal = params[akey];
		return curVal ? acc += `${akey}=${curVal};` : acc;
	}, `${key}=${encodeURIComponent(value)};`);
	document.cookie = result;
}

export function delCookie(key: string) {
	document.cookie = `${key}=;expires=-1`;
}
// 根据区code获取所在地
export function getCityText(code: any) {
	const strCode = code + '';
	const province = strCode.substring(0, 2) + '0000000000';
	const city = strCode.substring(0, 4) + '00000000';
	const area = strCode.substring(0, 6) + '000000';
	let text = '';
	cityData.map((item: any, index) => {
		if (item.id == province) {
			text = item.label;
			if (item.children) {
				item.children.map((el:any, idx:any) => {
					if (el.id == city) {
						text = text + '/' + el.label;
						if (el.children) {
							el.children.map((e:any, i:any) => {
								if (e.id == area) {
									text = text + '/' + e.label;
								}
							})
						}
					}
				})
			}

		}
	})
	return text
}

// 返回区县
export function getAreaText(code: any) {
	const strCode = code + '';
	const province = strCode.substring(0, 2) + '0000000000';
	const city = strCode.substring(0, 4) + '00000000';
	const area = strCode.substring(0, 6) + '000000';
	let text = '';
	cityData.map((item: any, index) => {
		if (item.id == province) {
			text = item.label;
			if (item.children) {
				item.children.map((el: any, idx: any) => {
					if (el.id == city) {
						// text = text + '/' + el.label;
						if (el.children) {
							el.children.map((e: any, i: any) => {
								if (e.id == area) {
									text = e.label;
								}
							})
						}
					}
				})
			}

		}
	})
	return text
}


export function getJudgePermissions() {
	return true
}

export function convertCurrency(money: any) {
	// 传入的参数为空情况 
	if (money == '') {
		return '';
	}
	let m = money;
	//最大处理的数字
	const maxNum = 999999999999999.9999;

	m = parseFloat(money)
	if (m >= maxNum) {
		return ''
	}
	//汉字的数字
	const cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
	//基本单位
	const cnIntRadice = new Array('', '拾', '佰', '仟');
	//对应整数部分扩展单位
	const cnIntUnits = new Array('', '万', '亿', '兆');
	//对应小数部分单位
	const cnDecUnits = new Array('角', '分', '毫', '厘');
	//整数金额时后面跟的字符
	const cnInteger = '整';
	//整型完以后的单位
	const cnIntLast = '元';

	//金额整数部分
	let integerNum;
	//金额小数部分
	let decimalNum;
	//输出的中文金额字符串
	let chineseStr = '';
	//分离金额后用的数组，预定义
	let parts;


	// 传入的参数为0情况 
	if (m == 0) {
		chineseStr = cnNums[0] + cnIntLast + cnInteger;
		return chineseStr
	}
	// 转为字符串
	m = m.toString();
	// indexOf 检测某字符在字符串中首次出现的位置 返回索引值（从0 开始） -1 代表无
	if (m.indexOf('.') == -1) {
		integerNum = m;
		decimalNum = ''
	} else {
		parts = m.split('.');
		integerNum = parts[0];
		decimalNum = parts[1].substr(0, 4);
	}
	//转换整数部分
	if (parseInt(integerNum, 10) > 0) {
		let zeroCount = 0;
		const IntLen = integerNum.length
		for (let i = 0; i < IntLen; i++) {
			const n = integerNum.substr(i, 1);
			const p = IntLen - i - 1;
			const q = p / 4;
			const m = p % 4;
			if (n == '0') {
				zeroCount++;
			} else {
				if (zeroCount > 0) {
					chineseStr += cnNums[0]
				}
				zeroCount = 0;
				chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
			}
			if (m == 0 && zeroCount < 4) {
				chineseStr += cnIntUnits[q];
			}
		}
		// 最后+ 元
		chineseStr += cnIntLast;
	}
	// 转换小数部分
	if (decimalNum != '') {
		const decLen = decimalNum.length;
		for (let i = 0; i < decLen; i++) {
			const n = decimalNum.substr(i, 1);
			if (n != '0') {
				chineseStr += cnNums[Number(n)] + cnDecUnits[i]
			}
		}
	}
	if (chineseStr == '') {
		chineseStr += cnNums[0] + cnIntLast + cnInteger;
	} else if (decimalNum == '') {
		chineseStr += cnInteger;
	}

	return chineseStr
}

// 阿拉伯数字转中文数字
export function getNumber(num: any) {
	// 传入的参数为空情况 
	if (num == '') {
		return '';
	}
	let m = num;

	//汉字的数字
	const cnNums = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
	//基本单位
	const cnIntRadice = new Array('', '十', '百', '千');
	//对应整数部分扩展单位
	const cnIntUnits = new Array('', '万', '亿', '兆');


	//金额整数部分
	let integerNum;
	//金额小数部分
	let decimalNum;
	//输出的中文金额字符串
	let chineseStr = '';

	// 传入的参数为0情况 
	if (m == 0) {
		chineseStr = cnNums[0];
		return chineseStr
	}
	// 转为字符串
	m = m.toString();
	// indexOf 检测某字符在字符串中首次出现的位置 返回索引值（从0 开始） -1 代表无
	if (m.indexOf('.') == -1) {
		integerNum = m;
		decimalNum = ''
	}

	//转换整数部分
	if (parseInt(integerNum, 10) > 0) {
		let zeroCount = 0;
		const IntLen = integerNum.length
		for (let i = 0; i < IntLen; i++) {
			const n = integerNum.substr(i, 1);
			const p = IntLen - i - 1;
			const q = p / 4;
			const m = p % 4;
			if (n == '0') {
				zeroCount++;
			} else {
				if (zeroCount > 0) {
					chineseStr += cnNums[0]
				}
				zeroCount = 0;
				chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
			}
			if (m == 0 && zeroCount < 4) {
				chineseStr += cnIntUnits[q];
			}
		}
	}

	if (chineseStr == '') {
		chineseStr += cnNums[0];
	}
	return chineseStr
}
